
// src/hooks/useKeyboard.ts
import { useEffect } from 'react';

interface KeyBinding {
  key: string;
  ctrl?: boolean;
  alt?: boolean;
  shift?: boolean;
  meta?: boolean;
  handler: (event: KeyboardEvent) => void;
}

/**
 * 键盘快捷键 Hook
 */
export const useKeyboard = (bindings: KeyBinding[]) => {
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      for (const binding of bindings) {
        const ctrlMatch = binding.ctrl === undefined || binding.ctrl === event.ctrlKey;
        const altMatch = binding.alt === undefined || binding.alt === event.altKey;
        const shiftMatch = binding.shift === undefined || binding.shift === event.shiftKey;
        const metaMatch = binding.meta === undefined || binding.meta === event.metaKey;
        const keyMatch = binding.key.toLowerCase() === event.key.toLowerCase();

        if (ctrlMatch && altMatch && shiftMatch && metaMatch && keyMatch) {
          event.preventDefault();
          binding.handler(event);
          break;
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [bindings]);
};